#！/usr/bin/env python
#!coding=utf-8

from fileinput import filename
import os
import sys
import csv
import json

def run():
    filename = "./data/student.csv"
    # read sth in filename
    data = csv.reader(open(filename, 'r', encoding="utf-8", newline="\n"))
    result = []
    for line in data:
        linenum = data.line_num
        line[-1] = line[-1].strip('\n')
        arr = [linenum] + line
        print(arr)
        result.append(arr)
    writefile = "./data/from_student.csv"
    print(result)
    with open(writefile, 'w', encoding="utf-8", newline="\n") as f:
        csv_writer_obj = csv.writer(f)
        csv_writer_obj.writerows(result)
def json_part():
    # dump json
    books = [
        {
            'title': '钢铁是怎样练成的',
            'price': 9.8
        },
        {
            'title': '红楼梦',
            'price': 9.9
        }
    ]
    json_str = json.dumps(books, ensure_ascii=False)
    print(json_str)  #dumps成数据流和pickle有点儿类似
    #如果要flush到本地文件要用dump
    filename = "./data/book.json"
    with open(filename,'w', encoding="utf-8") as fp:
        json.dump(books,fp, ensure_ascii=False)
    
    #字符串到json格式对象
    json_str = '[{"title": "钢铁是怎样练成的", "price": 9.8}, {"title": "红楼梦", "price": 9.9}]'
    #books = json.loads(json_str, encoding='utf-8')
    books = json.loads(json_str)
    print(type(books))
    print(books)


    #直接load json文件
    print("load json from local file")
    with open(filename,'r',encoding='utf-8') as fp:
        json_str = json.load(fp)
        print(json_str)

if __name__ == "__main__":
    #run()
    json_part()